#ifndef _SHARED_PTR_H_
#define _SHARED_PTR_H_

namespace Medved
{

// dumb :)
	
template <class T>
class SharedPtr
{
public:

	SharedPtr() :
		counter_(0), obj_(0)
	{}
	
	SharedPtr(T *obj) :
		counter_(new int(1)), obj_(obj)
	{}
	
	SharedPtr(const SharedPtr &rhs) :
		counter_(rhs.counter_), obj_(rhs.obj_)
	{
		if (counter_)
			++(*counter_);
	}
	
	SharedPtr &operator =(const SharedPtr &rhs)
	{
		drop_();
		counter_ = rhs.counter_;
		obj_ = rhs.obj_;
		if (counter_)
			++(*counter_);
		
		return *this;
	}

	SharedPtr &operator =(T *obj)
	{
		drop_();
		counter_ = new int(1);
		obj_ = obj;
		
		return *this;
	}
	
	T *operator ->() const
	{
		return obj_;
	}

	operator const void *() const
	{
		return obj_;
	}
	
	~SharedPtr()
	{
		drop_();
	}

private:
	void drop_()
	{
		if (obj_) {
			--(*counter_);
			if (!*counter_) {
				delete obj_;
				delete counter_;
			}
			counter_ = 0;
			obj_ = 0;
		}
	}
	
	int *counter_;
	T *obj_;
};

}

#endif
